package net.wofly.sale.activity.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import net.wofly.common.condition.Condition;
import net.wofly.common.condition.ConditionRelate;
import net.wofly.common.condition.ConditionUtil;
import net.wofly.common.condition.FilterCondition;
import net.wofly.common.condition.Operation;
import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.CommonStatus;
import net.wofly.common.util.DateUtil;
import net.wofly.common.util.Identities;
import net.wofly.common.util.PageHelper;
import net.wofly.framework.util.ResultCode;
import net.wofly.framework.util.ReturnBean;
import net.wofly.sale.activity.domain.Activity;
import net.wofly.sale.activity.domain.ActivityGift;
import net.wofly.sale.activity.repository.ActivityRepository;
import net.wofly.sale.activity.service.IActivityGiftService;
import net.wofly.sale.activity.service.IActivityService;
import net.wofly.sale.activity.util.ActivityStatus;
import net.wofly.sale.activity.util.ActivityType;
import net.wofly.sale.commodity.domain.Commodity;
import net.wofly.sale.commodity.domain.CommodityChannel;
import net.wofly.sale.commodity.domain.CommodityTerminal;
import net.wofly.sale.commodity.service.ICommodityChannelService;
import net.wofly.sale.commodity.service.ICommodityService;
import net.wofly.sale.commodity.service.ICommodityTmlService;
import net.wofly.sale.order.util.OrderType;

@Service("iActivityService")
@Transactional
public class ActivityServiceImpl implements IActivityService {
    
    Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class);
    
    @Autowired
    ActivityRepository activityRepository;
    
    @Autowired
    IActivityGiftService iActivityGiftService;
    
    @Autowired
    ICommodityService iCommodityService;
    
    @Autowired
    ICommodityTmlService iCommodityTerminalService;
    
    @Autowired
    ICommodityChannelService iCommodityChannelService;
    
    @Override
    public Activity save(Activity entity) {
        return activityRepository.save(entity);
    }
    
    @Override
    public void delete(Activity entity) {
        activityRepository.delete(entity);
    }
    
    @Override
    public void delete(String key) {
        activityRepository.delete(key);
    }
    
    @Override
    public Activity findOne(String key) {
        return activityRepository.findOne(key);
    }
    
    @Override
    public List<Activity> save(List<Activity> entityList) {
        return (List<Activity>) activityRepository.save(entityList);
    }
    
    @Override
    public List<Activity> findByCommodityChannelIDAndStatusAndStartTimeBeforeAndEndTimeAfter(
            String commodityChannelID, Integer status, long nowTime1, long nowTime2) {
        return activityRepository.findByCommodityChannelIDAndStatusAndStartTimeBeforeAndEndTimeAfter(commodityChannelID,
                status, nowTime1, nowTime2);
    }
    
    @Override
    public List<Activity> findByOrderTypeAndCommodityChannelIDAndStatusAndStartTimeBeforeAndEndTimeAfter(
            Integer orderType, String commodityChannelID, Integer status, long nowTime1, long nowTime2) {
        return activityRepository.findByOrderTypeAndCommodityChannelIDAndStatusAndStartTimeBeforeAndEndTimeAfter(
                orderType, commodityChannelID, status, nowTime1, nowTime2);
    }
    
    @Override
    public List<Activity> findByActivityType(Integer activityType) {
        return activityRepository.findByActivityType(activityType);
    }
    
    @Override
    public List<Activity> findByActivityTypeAndStatusAndStartTimeBeforeAndEndTimeAfter(
            Integer activityType, Integer status, long nowTime1, long nowTime2) {
        return activityRepository.findByActivityTypeAndStatusAndStartTimeBeforeAndEndTimeAfter(activityType, status,
                nowTime1, nowTime2);
    }
    
    public Page<Activity> findAll(Specification specification, Pageable pageable) {
        return activityRepository.findAll(specification, pageable);
    }
    
    public List<Activity> findAll(Specification specification) {
        return activityRepository.findAll(specification);
    }
    
    public List<Activity> findAll(Specification specification, Sort sort) {
        return activityRepository.findAll(specification, sort);
    }
    
    @Override
    public ReturnBean<Activity> addActivity(Activity activity) {
    		if (checkRepeatActivity(activity) ==1) {
    			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "新增活动失败，与己有有效活动重复！");
    		}
    		
        String activityID = Identities.uuid2();
        long modifyDate = System.currentTimeMillis();
        activity.setActivityID(activityID);
        activity.setModifyDate(modifyDate);
        
        if (null != activity.getStartTime()) {
            activity.setStartTime(DateUtil.processStartTime(new Date(activity.getStartTime())).getTime());
        }
        
        if (null != activity.getEndTime()) {
            activity.setEndTime(DateUtil.processStartTime(new Date(activity.getEndTime())).getTime());
        }
        
        // TODO  Q:是不是缺少设置活动生效的方法  A: 创建订单直接设置为生效状态， 结合开始时间和结束时间
        activity.setStatus(ActivityStatus.草稿.getValue());
        
        List<ActivityGift> activityGifts = activity.getActivityGifts();
        if (!CollectionUtils.isEmpty(activityGifts)) {
            for (ActivityGift activityGift : activityGifts) {
                activityGift.setActivityGiftID(Identities.uuid2());
                activityGift.setActivityID(activityID);
                activityGift.setModifyDate(modifyDate);
            }
        }
        return new ReturnBean<>(ResultCode.SUCCESS, "新增活动成功", save(activity));
    }
    
    private Integer checkRepeatActivity(Activity activity) {
    		int repeatFlag = 1 ;
    		/*
    		 * 单一商品数量累计-每满赠
    		 * 在其有效时间内，同一个种订单，同一个渠道商品下是否有活动
    		 * 
    		 */
    		if (ActivityType.单一商品数量累计_每满赠.getValue().equals(activity.getActivityType())) {
    			List<Activity> activitys = activityRepository.findByCommodityChannelIDAndStartTimeAndEndTime(activity.getOrderType(), activity.getCommodityChannelID(), activity.getStartTime(), activity.getEndTime()) ;
    			if (null==activitys || activitys.isEmpty()) {  //
    				repeatFlag = 0 ;
    			}
    		}else if (ActivityType.单一订单中商品总价.getValue().equals(activity.getActivityType())) {
    			List<Activity> activitys = activityRepository.findByOrderTypeAndStartTimeAndEndTime(activity.getOrderType(), activity.getStartTime(), activity.getEndTime()) ;
    			if (null==activitys || activitys.isEmpty()) {  //
    				repeatFlag = 0 ;
    			}
    		}
    		
    		return repeatFlag ;
    }
    
    @Override
    public ReturnBean<List<ActivityGift>> addActivityGift(String activityID, ActivityGift activityGift) {
        activityGift.setActivityID(activityID);
        activityGift.setModifyDate(System.currentTimeMillis());
        iActivityGiftService.save(activityGift);
        Activity activity = findOne(activityID);
        return new ReturnBean<>(ResultCode.SUCCESS, "添加成功", activity.getActivityGifts());
    }
    
    @Override
    public ReturnBean<String> delActivity(String activityID) {
        Activity activity = findOne(activityID);
        if (activity == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "活动ID（activityID）不正确");
        }
        
        if (activity.getStatus().equals(ActivityStatus.草稿.getValue())) {
        		delete(activityID) ;
        		iActivityGiftService.deleteByActivityID(activityID);
        		return new ReturnBean<>(ResultCode.SUCCESS, "删除成功");
        }
        
        if (activity.getStatus().equals(ActivityStatus.发布.getValue())) {
        		activity.setStatus(ActivityStatus.下线.getValue());
            activity.setModifyDate(System.currentTimeMillis());
            save(activity);
            return new ReturnBean<>(ResultCode.SUCCESS, "删除成功");
        }
        
        return new ReturnBean<>(ResultCode.SUCCESS, "删除成功");
    }
    
    @Override
    public List<Activity> findByActivityIDIn(List<String> activityIDs) {
        return activityRepository.findByActivityIDIn(activityIDs);
    }
    
    @Override
    public ReturnBean<PageWrapper<Activity>> getAllActivity(
            String activityName, Long startTime, Integer status, Integer pageNum, Integer pageSize) {
        Condition condition = new Condition();
        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
        long now = System.currentTimeMillis();
        if (status != null) {
            filterConditions.add(new FilterCondition(String.valueOf(status), "status", ConditionRelate.and.name(),
                    Operation.eq.name(), 1));
            /*if (status.intValue() == ActivityStatus.发布.getValue()) {
                filterConditions.add(new FilterCondition(String.valueOf(now), "startTime", ConditionRelate.and.name(),
                        Operation.lt.name(), 2));
                filterConditions.add(new FilterCondition(String.valueOf(now), "endTime", ConditionRelate.and.name(),
                        Operation.gt.name(), 3));
            } else if (status.intValue() == ActivityStatus.下线.getValue()) {
                filterConditions.add(new FilterCondition(String.valueOf(now), "endTime", ConditionRelate.and.name(),
                        Operation.lt.name(), 3));
            }*/
        }
        
        if (!StringUtils.isEmpty(activityName)) {
            filterConditions.add(
                    new FilterCondition(activityName , "activityName", ConditionRelate.and.name(),
                            Operation.like.name(), 4));
        }
        
        if (null != startTime) {
            filterConditions.add(
                    new FilterCondition(String.valueOf(DateUtil.processStartTime(new Date(startTime)).getTime()),
                            "startTime", ConditionRelate.and.name(), Operation.eq.name(), 5));
        }
        
        condition.setFilterCondition(filterConditions);
        
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), Activity.class).getResult();
        
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, new Sort(Sort.Direction.DESC, "modifyDate"));
        Page<Activity> page = findAll(condition.getSpecification(), pageable);
        List<Activity> activityList = page.getContent();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(activityList)) {
            for (Activity activity : activityList) {
            		buildCommodityTerminal(activity.getActivityGifts());
            		if (!StringUtils.isEmpty(activity.getOrderType())) {
            			if(activity.getOrderType().equals(-1)) {
            				activity.setOrderTypeStr("所有订单");
            			}else {
            				activity.setOrderTypeStr(OrderType.getName(activity.getOrderType()));
            			}
            		}
            }
        }
        return new ReturnBean<PageWrapper<Activity>>(ResultCode.SUCCESS, "查询成功", PageHelper.toPage(page));
    }
    
    private void buildCommodityTerminal(List<ActivityGift> activityGifts) {
        for (ActivityGift activityGift : activityGifts) {
        		if (!StringUtils.isEmpty(activityGift.getCommodityTerminalID())) {
        			CommodityTerminal commodityTerminal = iCommodityTerminalService.findOne(activityGift.getCommodityTerminalID());
        			
            		activityGift.setCommodityTerminal(commodityTerminal) ;
            }
            
        }
    }
    
    
    
    @Override
    public ReturnBean<List<Activity>> getCommodityActivity(String commodityChannelID) {
        Condition condition = new Condition();
        List<FilterCondition> filterConditions = new ArrayList<FilterCondition>();
        long now = System.currentTimeMillis();
/*        filterConditions.add(
                new FilterCondition(String.valueOf(ActivityStatus.发布), "status", ConditionRelate.and.name(),
                        Operation.eq.name(), 1));
        filterConditions.add(new FilterCondition(String.valueOf(now), "startTime", ConditionRelate.and.name(),
                Operation.lt.name(), 2));
        filterConditions.add(new FilterCondition(String.valueOf(now), "endTime", ConditionRelate.and.name(),
                Operation.gt.name(), 3));*/
        
        filterConditions.add(
                new FilterCondition(commodityChannelID, "commodityChannelID", ConditionRelate.and.name(),
                        Operation.eq.name(), 1));
        
        condition.setFilterCondition(filterConditions);
        
        condition = ConditionUtil.buildCondition(XiNiaoJSON.toJSONString(condition), Activity.class).getResult();
        
        List<Activity> activityList = findAll(condition.getSpecification(),
                new Sort(Sort.Direction.DESC, "modifyDate"));
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(activityList)) {
            for (Activity activity : activityList) {
            		buildCommodityTerminal(activity.getActivityGifts());
            }
        }
        return new ReturnBean<List<Activity>>(ResultCode.SUCCESS, "查询成功", activityList);
    }
    
    @Override
    public ReturnBean<Activity> modifyActivity(Activity activity) {
        Activity dbActivity = findOne(activity.getActivityID());
        if (dbActivity == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "活动ID（activityID）不正确");
        }
        if (dbActivity.getStatus().intValue() != ActivityStatus.草稿.getValue()) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "活动已发布或下线，不能修改");
        }
        
        if (checkRepeatActivity(activity) ==1) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "新增活动失败，与己有活动重复！");
		}
        
        activity.setModifyDate(System.currentTimeMillis());
        activity.setStatus(dbActivity.getStatus());
        activity.setActivityGifts(dbActivity.getActivityGifts());
        save(activity);
        return new ReturnBean<>(ResultCode.SUCCESS, "修改成功");
    }
    
    @Override
    public ReturnBean<List<ActivityGift>> addActivityGifts(
            String activityID, List<ActivityGift> activityGifts) {
        Activity activity = findOne(activityID);
        if (null == activity) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "活动ID（activityID）不正确");
        }
        if (ActivityStatus.草稿.getValue().intValue() != activity.getStatus()) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "活动已发布或下线，不能修改");
        }
        
        //删除原有的
        iActivityGiftService.deleteByActivityID(activityID);
        
        for (ActivityGift gift : activityGifts) {
            gift.setActivityID(activityID);
            gift.setModifyDate(System.currentTimeMillis());
            if (StringUtils.isEmpty(gift.getActivityGiftID())) {
                gift.setActivityGiftID(Identities.uuid2());
            }
        }
        
        return new ReturnBean<>(ResultCode.SUCCESS, "添加成功", iActivityGiftService.save(activityGifts));
    }
    
    @Override
    public ReturnBean<List<ActivityGift>> getActivityGift(String activityID) {
        
        List<ActivityGift> activityGift = iActivityGiftService.findByActivityID(activityID);
        if (!CollectionUtils.isEmpty(activityGift)) {
        		buildCommodityTerminal(activityGift);
        }
        
        return new ReturnBean<List<ActivityGift>>(ResultCode.SUCCESS, "添加成功", activityGift);
    }
    
    @Override
    public ReturnBean<Activity> publishActivity(String activityID) {
        Activity dbActivity = findOne(activityID);
        if (dbActivity == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "活动ID（activityID）不正确");
        }
        if (dbActivity.getStatus().intValue() != ActivityStatus.草稿.getValue()) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "活动已发布或下线，不能发布");
        }
        
        List<ActivityGift> activityGifts = iActivityGiftService.findByActivityID(activityID) ;
        if (null == activityGifts || activityGifts.isEmpty()) {
        		return new ReturnBean<>(ResultCode.ERROR_SERVICE, "没有为活动配置赠品，不能发布");
        }
        
        dbActivity.setModifyDate(System.currentTimeMillis());
        dbActivity.setStatus(ActivityStatus.发布.getValue());
        return new ReturnBean<>(ResultCode.SUCCESS, "发布成功", save(dbActivity));
    }
    
    @Override
    public ReturnBean<Activity> offlineActivity(String activityID) {
        Activity dbActivity = findOne(activityID);
        if (dbActivity == null) {
            return new ReturnBean<>(ResultCode.ERROR_SERVICE, "活动ID（activityID）不正确");
        }
        dbActivity.setModifyDate(System.currentTimeMillis());
        dbActivity.setStatus(ActivityStatus.下线.getValue());
        
        return new ReturnBean<>(ResultCode.SUCCESS, "下线成功", save(dbActivity));
    }
    
    @Override
    public ReturnBean<Activity> getActivityByID(String activityID) {
        Activity activity = findOne(activityID);
        if (null != activity) {
        		if (ActivityType.单一商品数量累计_每满赠.getValue().equals(activity.getActivityType())) {
        			CommodityChannel commodityChannel = iCommodityChannelService.findOne(activity.getCommodityChannelID());
                activity.setCommodityChannel(commodityChannel);
        		}
            
            if (activity.getOrderType().equals(-1)) {
            		activity.setOrderTypeStr("所有订单");
            }else {
            		activity.setOrderTypeStr(OrderType.getName(activity.getOrderType()));
            }
        }
        
        return new ReturnBean<>(ResultCode.SUCCESS, "获取成功", activity);
    }

	@Override
	public ReturnBean<List<Activity>> getActivityByOrderTypeAndActivityType(Integer orderType, Integer activityType) {
        Long sysDate = System.currentTimeMillis();
        List<Activity> activities = activityRepository
                .findByOrderTypeAndActivityTypeAndStatusAndStartTimeBeforeAndEndTimeAfter(
                        orderType, activityType, ActivityStatus.发布.getValue(), sysDate, sysDate);
        if (!CollectionUtils.isEmpty(activities)) {
            for (Activity activity : activities) {
                String commodityChannelID = activity.getCommodityChannelID();
                CommodityChannel channel = iCommodityChannelService.findOne(commodityChannelID);
                activity.setCommodityChannel(channel);
                if (null!=channel) {
	            		Commodity commodity = iCommodityService.findOne(channel.getCommodityID()) ;
	            		activity.setCommodity(commodity);
	            }
           
                List<ActivityGift> activityGifts = activity.getActivityGifts();
                if (!CollectionUtils.isEmpty(activityGifts)) {
                    for (ActivityGift activityGift : activityGifts) {
                        String commodityTerminalID = activityGift.getCommodityTerminalID();
                        CommodityTerminal terminal = iCommodityTerminalService.findOne(commodityTerminalID);
                        activityGift.setCommodityTerminal(terminal);
                        if (null!=terminal) {
		    	            		Commodity commodity = iCommodityService.findOne(terminal.getCommodityID()) ;
		    	            		activityGift.setCommodity(commodity);
		    	            }
                    }
                }
            }
        }
        return new ReturnBean<>(ResultCode.SUCCESS, "获取活动列表成功！", activities);
    }
}
